package com.dys.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @className: com.dys.servlet.Servlet01
 * @description: ServletContext上下文对象
 * @author: pine cone
 * @version: v1.0.0
 * @createTime: 2024/09/19 22:25
 */
public class Servlet01 extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.获取Servlet对象的方式
        // 通过req对象
        ServletContext servletContext1 = req.getServletContext();
        // 通过继承的方式获取
        ServletContext servletContext2 = this.getServletContext();
        System.out.println(servletContext1 == servletContext2);

        // 获取当前项目的部署名
        String contextPath = servletContext1.getContextPath();
        System.out.println("当前项目部署名：" + contextPath);

        // 将一个相对路径转化为项目的绝对路径
        String fileUpload = servletContext1.getRealPath("fileUpload");
        System.out.println("相对路径转为绝对路径：" + fileUpload);

        // 获取Tomcat服务器信息
        String serverInfo = servletContext1.getServerInfo();
        System.out.println("Tomcat服务器信息：" + serverInfo);

        // servlet版本
        int majorVersion = servletContext1.getMajorVersion();
        System.out.println("Servlet主版本号：" + majorVersion);
        int minorVersion = servletContext1.getMinorVersion();
        System.out.println("Servlet副版本号：" + minorVersion);

        // 获取web.xml中配置的全局的初始信息
        String username = servletContext1.getInitParameter("username");
        System.out.println("ServletContext中配置的账号：" + username);
        String password = servletContext1.getInitParameter("password");
        System.out.println("ServletContext中配置的密码：" + password);

        // 向ServletContext对象中增加数据 域对象
        List<String> list = new ArrayList<String>();
        Collections.addAll(list, "张三", "李四", "王五", "赵六");
        servletContext1.setAttribute("list", list);
        servletContext1.setAttribute("sex", "男");
    }
}
